import YAML from 'yaml'
import chokidar from 'chokidar'
import fs from 'node:fs'
import {_path, configPath, defaultPath} from "./path.js";

class Setting {
    constructor() {
        /** 默认设置 */
        this.def = {}
        /** 用户设置 */
        this.config = {}
        /** 监听文件 */
        this.watcher = {config: {}, def: {}}
    }

    // 配置对象化 用于锅巴插件界面填充
    merge() {
        let sets = {}
        let appsConfig = fs.readdirSync(defaultPath).filter(file => file.endsWith(".yaml"));
        for (let appConfig of appsConfig) {
            // 依次将每个文本填入键
            let filename = appConfig.replace(/.yaml/g, '').trim()
            sets[filename] = this.getConfig(filename)
        }
        return sets
    }

    // 配置对象分析 用于锅巴插件界面设置
    analysis(config) {
        for (let key of Object.keys(config)) {
            this.setConfig(key, config[key])
        }
    }

    // 获取对应模块默认配置
    getdefSet(app) {
        return this.getYaml(app, 'def')
    }

    // 获取对应模块用户配置
    getConfig(app) {
        return {...this.getdefSet(app), ...this.getYaml(app, 'config')}
    }

    // 设置对应模块用户配置
    setConfig(app, Object) {
        Object = this.ObjectFilter(app, Object)
        return this.setYaml(app, 'config', {...this.getdefSet(app), ...Object})
    }

    // 设置字段过滤处理，待抽象
    ObjectFilter(app, Object) {
        if (app === 'application') {
            let fields = ['absoluteMaster', 'maxHitTimes']
            for (let field of fields) {
                if (Object.hasOwnProperty(field)) {
                    Object[field] = parseInt(Object[field])
                }
            }
        }

        return Object
    }

    // 将对象写入YAML文件
    setYaml(app, type, Object) {
        let file = this.getFilePath(app, type)
        try {
            fs.writeFileSync(file, YAML.stringify(Object), 'utf8')
        } catch (error) {
            logger.error(`[${app}] 写入失败 ${error}`)
            return false
        }
    }

    // 读取YAML文件 返回对象
    getYaml(app, type) {
        let file = this.getFilePath(app, type)
        if (this[type][app]) return this[type][app]

        try {
            this[type][app] = YAML.parse(fs.readFileSync(file, 'utf8'))
        } catch (error) {
            logger.error(`[${app}] 格式错误 ${error}`)
            return false
        }
        this.watch(file, app, type)
        return this[type][app]
    }

    // 获取YAML文件目录
    getFilePath(app, type) {
        if (type === 'def') return `${defaultPath}${app}.yaml`
        else {
            try {
                if (!fs.existsSync(`${configPath}${app}.yaml`)) {
                    fs.copyFileSync(`${defaultPath}${app}.yaml`, `${configPath}${app}.yaml`)
                }
            } catch (error) {
                logger.error(`自动化插件缺失默认文件[${app}]${error}`)
            }
            return `${configPath}${app}.yaml`
        }
    }


    // 监听配置文件
    watch(file, app, type = 'def') {
        if (this.watcher[type][app]) return

        const watcher = chokidar.watch(file)
        watcher.on('change', path => {
            delete this[type][app]
            logger.mark(`[自动化插件][修改配置文件][${type}][${app}]`)
            if (this[`change_${app}`]) {
                this[`change_${app}`]()
            }
        })
        this.watcher[type][app] = watcher
    }
}

export default new Setting()
